﻿using Basic.Cluster.Abstract;
using Basic.Cluster.Impl;
using Basic.Cluster.Manager;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace System;

public static class ClusterExtension
{
    /// <summary>
    /// Consul注册配置
    /// </summary>
    /// <param name="services"></param>
    /// <param name="section"></param>
    /// <returns></returns>
    public static IServiceCollection AddClusterRegister(this IServiceCollection services, IConfigurationSection section)
    {
        var config = section.Get<ClusterConfig>();
        if (config != null)
        {
            IRegister register = null;
            if (string.Equals(config.ClusterManagerProxy, "Consul", StringComparison.OrdinalIgnoreCase))
                register = new ConsulRegister();

            register.AddRegister(services, config);
            services.AddSingleton<IRegister>(register);
        }
        return services;
    }

    /// <summary>
    /// 启用Consul注册
    /// </summary>
    /// <param name="app"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseClusterRegister(this IApplicationBuilder app)
    {
        var provider = app.ApplicationServices;

        // 获取主机生命周期对象
        var register = provider.GetRequiredService<IRegister>();
        register.UseRegister(app);

        return app;
    }

}